<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <div>
        <el-row :gutter="20">
          <el-col :span="9"><div class="grid-content bg-purple">
            <el-input clearable placeholder="请输入内容" v-model="queryInfo.query" @clear="getUserslist">
              <el-button slot="append" icon="el-icon-search" @click="getUserslist"></el-button>
            </el-input></div></el-col>
          <el-col :span="6"><div class="grid-content bg-purple">
            <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
          </div></el-col>
        </el-row>
      </div>
      <!-- 用户列表区域 -->
      <el-table
      border
      :data="usersList">
      <el-table-column
        type="index"
        label="#">
      </el-table-column>
      <el-table-column
        prop="username"
        label="姓名">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="create_time"
        label="电话">
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="角色">
      </el-table-column>
      <el-table-column
        label="状态">
        <template
        slot-scope="slotScope">
          <el-switch
            v-model="slotScope.row.mg_state"
            @change="changeUserState(slotScope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        width="180px"
        label="操作">
        <template
         slot-scope="slotScope">
          <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
            <el-button @click="modiUser(slotScope.row.id)" type="primary" icon="el-icon-edit" size="mini"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
            <el-button @click="delUser(slotScope.row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
            <el-button @click="addRlose(slotScope.row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页功能 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[2, 4, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addDialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="modiDialogVisible"
      width="50%"
      @close="modiDialog">
      <el-form
      :model="modiForm"
      :rules="addFormRules"
      ref="modiFormRef"
      label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="modiForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="modiForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="modiForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="modiDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="modiUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="showRolesDialog"
      width="50%"
      @close="setCloseRlose">
      <p><span>当前用户：{{userRloseList.username}}</span></p>
      <p><span>当前角色：{{userRloseList.role_name}}</span></p>
      <span>添加角色</span>
      <el-select v-model="selectRloseId" placeholder="请选择">
        <el-option
          v-for="item in rloseList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveRloseInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义校验规则
    var changeEmail = (rule, value, callback) => {
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (!regEmail.test(value)) {
        callback(new Error('请输入合法的邮箱'))
      }
      callback()
    }
    var changeMobile = (rule, value, callback) => {
      const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (!regMobile.test(value)) {
        callback(new Error('请输入合法的手机号码'))
      }
      callback()
    }
    return {
      // 请求参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      usersList: [],
      total: 0,
      userRloseList: {},
      rloseList: {},
      // 选中的角色
      selectRloseId: '',
      // 控制添加用户的弹出框显示或者隐藏
      dialogVisible: false,
      // 控制修改用户的弹出框
      modiDialogVisible: false,
      // 控制分配角色的弹出框
      showRolesDialog: false,
      // 添加用户表单
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单验证
      addFormRules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: changeEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: changeMobile, trigger: 'blur' }
        ]
      },
      // 修改用户的表单信息
      modiForm: {}
    }
  },
  created() {
    this.getUserslist()
  },
  methods: {
    async getUserslist() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('请求用户列表失败！')
      this.usersList = res.data.users
      this.total = res.data.total
    },
    // 每页有多少条数据
    handleSizeChange(countsize) {
      this.queryInfo.pagesize = countsize
      this.getUserslist()
    },
    // 当前页码
    handleCurrentChange(currentChange) {
      this.queryInfo.pagenum = currentChange
      this.getUserslist()
    },
    async changeUserState(user) {
      const { data: res } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      if (res.meta.status !== 200) {
        res.data.mg_state = !res.data.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 重置添加表单
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 重置修改表单
    modiDialog() {
      this.$refs.modiFormRef.resetFields()
    },
    // 对添加用户表单进行预验证 如果通过发起请求
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.dialogVisible = false
        this.getUserslist()
      })
    },
    // 对修改用户表单进行预验证 如果通过发起请求modiDialogVisible = false
    modiUserInfo() {
      this.$refs.modiFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`users/${this.modiForm.id}`, {
          email: this.modiForm.email,
          mobile: this.modiForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.modiDialogVisible = false
        this.getUserslist()
      })
    },
    // 删除用户
    async delUser(id) {
      const confirmRestul = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 点击确定按钮confirm
      // 点击取消cancel
      if (confirmRestul === 'cancel') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserslist()
    },
    // 修改用户
    async modiUser(id) {
      this.modiDialogVisible = true
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.modiForm = res.data
    },
    // 分配角色
    async addRlose(user) {
      this.userRloseList = user
      this.showRolesDialog = true
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rloseList = res.data
    },
    // 点击确定分配用户角色
    async saveRloseInfo() {
      if (!this.selectRloseId) return this.$message.error('请选择角色')
      const { data: res } = await this.$http.put(`users/${this.userRloseList.id}/role`, { rid: this.selectRloseId })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserslist()
      this.showRolesDialog = false
    },
    // 关闭对话框清空数据
    setCloseRlose() {
      this.userRloseList = {}
      this.selectRloseId = ''
      this.rloseList = {}
    }
  }
}
</script>

<style lang="less" scoped>
</style>
